//
//  WebEngine.m
//  WeiboSpace
//
//  Created by  linan4 on 12-3-6.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "WeiboHttpEngine.h"
#import "SBJSON.h"
//常量定义
#define SERVER_URL @"api.weibo.com"
#define WM_Value @""
#define UA_VALUE @""

@implementation WeiboHttpEngine

-(WeiboHttpEngine *) InitWeiboSpaceWithDelegate:(id)newDelegate {
	
	if (self = [super init]) {

		_delegate = newDelegate;
		
		//new NSMutabledata
		reslutData = [[NSMutableData alloc] initWithCapacity:0];
    }
    
    return self;
}
- (void)dealloc
{
    [reslutData release];
	_delegate = nil;

	[super dealloc];
}

#pragma mark Instance Funtions
-(void) SendHttpRequest:(EumWebMethod) method
					requestUrl:(NSString*) url
					urlParams:(NSDictionary *)urlParams
					bodyParams:(NSDictionary *)bodyparams
					accessToken:(NSString*) newAccessToken
{

	NSString *accessToken = newAccessToken;
	
	NSString *paramUrl = nil; 
	if (urlParams != nil) {
        paramUrl = [self _queryStringWithBase:url parameters:urlParams prefixed:YES];
    }
	
	//auto
    NSString *urlString = [NSString stringWithFormat:@"%@://%@/%@", 
						   @"https",
                           SERVER_URL, paramUrl];
    
    NSURL *finalURL = [NSURL URLWithString:urlString];
	
    if (!finalURL) 
	{
        return;
    }
	
    //NSMutableURLRequest
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL 
                                                              cachePolicy:NSURLRequestReloadIgnoringCacheData 
                                                          timeoutInterval:30.0];
		 
    if (method == Get) 
	{
		[theRequest setHTTPMethod:@"GET"];
	}
    else if(method == Post)
	{
		 [theRequest setHTTPMethod:@"POST"];
	}
    else
	{
		 //zanshi
		 [theRequest setHTTPMethod:@"GET"];
	}
		 
	 [theRequest setHTTPShouldHandleCookies:NO];
	 
	 // Set Normal headers
	 [theRequest setValue:UA_VALUE forHTTPHeaderField:@"User-Agent"];
	
	 //Set OAuth header
	 //TODO:Authorization:OAuth2空格abcd
	 if(accessToken != nil&&[accessToken length]!=0)
		 [theRequest setValue:[NSString stringWithFormat:@"OAuth2 %@",accessToken] forHTTPHeaderField:@"Authorization"];
	
	 
	NSString * finalBody = nil;
	 // Set the request body if this is a POST request.
	 if (bodyparams!=nil||[bodyparams count]>0)
	 {
		 finalBody = [self	_bodyStringWithbase:bodyparams];
		 
	 }
	 
	 if (finalBody) {
		 [theRequest setHTTPBody:[finalBody dataUsingEncoding:NSUTF8StringEncoding]];
	 }
	 
	 NSURLConnection *connection;
	 connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	 
	 if (nil == connection) {
		 return;
	 } else {
		 //[_connections setObject:connection forKey:[connection identifier]];
		 [connection release];
	 }
	 
}

#pragma mark NSURLConnection delegate methods		 
 - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
	
}
		 
		 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[reslutData setLength:0];
	

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	// Append the new data to the receivedData.
	[reslutData appendData:data];
}
 
 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	
	NSString *dataString = [[NSString alloc] initWithData:reslutData encoding:NSUTF8StringEncoding];
	SBJSON *jsonParser = [[SBJSON alloc]init];
	
	NSError *parseError = nil;
	id result = [jsonParser objectWithString:dataString error:&parseError];
	
	
	if (parseError)
    {
		//错误通知
		if(_delegate != nil && [_delegate respondsToSelector:@selector(DealJsonDataFinished)])
			[_delegate DealJsonDataException:parseError];
			[dataString release];
			[jsonParser release];	
		return;
	}
	
	//?这里为何检测不到？
	//if(_delegate != nil && [_delegate respondsToSelector:@selector(DealJsonDataFinished)])
	if(_delegate != nil ) {
		[_delegate DealJsonDataFinished:result];
	}
		
	//release
	[dataString release];
	[jsonParser release];
	
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
 
 	 
#pragma mark Tool Funtions
- (NSString *)_bodyStringWithbase:(NSDictionary*)params
{
	NSMutableString *str = [NSMutableString stringWithCapacity:0];
	if (params) {
        int i;
        NSArray *names = [params allKeys];
        for (i = 0; i < [names count]; i++) {
			
            if (i > 0&&i!=([names count]-1)) {
                [str appendString:@"&"];
            }
            NSString *name = [names objectAtIndex:i];
			NSString *value =(NSString*)[params objectForKey:name];
			if (value==nil || value== @"") {
				continue;
			}
            [str appendString:[NSString stringWithFormat:@"%@=%@", 
							   name, value]];
			
        }
    }
	
	return str;
}
- (NSString *)_queryStringWithBase:(NSString *)base parameters:(NSDictionary *)params prefixed:(BOOL)prefixed
{
	//retain
	[params retain];
	
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    if (base) {
        [str appendString:base];
    }
    
    // Append param to url
    if (params) {
        int i;
        NSArray *names = [params allKeys];
        for (i = 0; i < [names count]; i++) {
            if (i == 0 && prefixed) {
                [str appendString:@"?"];
            } else if (i > 0) {
                [str appendString:@"&"];
            }
            NSString *name = [names objectAtIndex:i];
			NSString *value =(NSString*)[params objectForKey:name];
			if (value==nil||value==@"") {
				continue;
			}
            [str appendString:[NSString stringWithFormat:@"%@=%@", 
							   name, value]];
        }
    }
	//release
    [params release];
    return str;
}
@end
